A for
loop is a type of loop construct that allows a block of code to be executed repeatedly for a fixed number of times. The
for
loop is typically used when the number of iterations is known in advance, and consists of three parts:
- The initialization statement is executed once at the beginning of the loop, and is used to initialize the loop counter or any other variables
that may be used in the loop.
- The loop condition is evaluated at the beginning of each iteration, and if it is
true
, the code inside the loop is executed.
- The update statement is executed at the end of each iteration, and is used to update the loop counter or any other variables that may be used
in the loop.
for (initialization; condition; update) { /*...*/ }
All three statements are optional. However, when the initialization and update statements are not used, it can be unclear to the reader what the
loop counter is and how it is being updated. This can make the code harder to understand and maintain.
for (;condition;) { /*...*/ } // Noncompliant: Only the condition is specified
When only the condition expression is defined in a for
loop, a while
loop should be used instead to increase readability.
A while
loop consists of a single loop condition and allows a block of code to be executed repeatedly as long as the specified condition
is true.
while (condition) { /*...*/ }